/**
 * 分页组件
 * 使用方法：
 * 1. 引入js文件
 * 2. 在HTML中添加分页容器: <div id="paginationContainer"></div>
 * 3. 初始化分页组件:
 *    const pagination = new Pagination({
 *      container: 'paginationContainer',
 *      onPageChange: (page, pageSize) => {
 *        // 处理页码变化
 *      }
 *    });
 * 4. 更新分页数据:
 *    pagination.update({
 *      pageNum: 1,
 *      pageSize: 10,
 *      total: 100,
 *      pages: 10
 *    });
 */
class Pagination {
    constructor(options) {
        this.container = document.getElementById(options.container);
        this.onPageChange = options.onPageChange;
        this.pageInfo = {
            pageNum: options.pageNum || 1,
            pageSize: options.pageSize || 10,
            total: options.total || 0
        };
        // 绑定方法到实例
        this.handlePageChange = this.handlePageChange.bind(this);
        this.addStyles();
        this.render();
    }
    
    init() {
        // 添加样式
        this.addStyles();
        
        // 创建分页容器
        this.container.className = 'pagination';
        this.container.innerHTML = `
            <span class="pagination-info">
                共 <span class="total-count">0</span> 条记录，
                每页 <select class="page-size-select">
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select> 条
            </span>
            <div class="page-buttons"></div>
            <div class="page-jump">
                跳至<input type="number" class="jump-input" min="1">页
                <button class="page-btn">确定</button>
            </div>
        `;
        
        // 绑定事件
        this.bindEvents();
    }
    
    addStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .pagination {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-top: 20px;
                gap: 15px;
            }
            .pagination-info {
                color: #666;
                font-size: 14px;
                white-space: nowrap;
            }
            .page-size-select {
                padding: 4px 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                margin: 0 5px;
                outline: none;
                cursor: pointer;
            }
            .page-buttons {
                display: flex;
                gap: 5px;
                align-items: center;
                white-space: nowrap;
            }
            .page-btn {
                padding: 5px 10px;
                border: 1px solid #d9d9d9;
                background: white;
                cursor: pointer;
                border-radius: 4px;
                min-width: 32px;
                text-align: center;
                font-size: 14px;
                transition: all 0.3s;
            }
            .page-btn:hover:not(.disabled) {
                border-color: #1890ff;
                color: #1890ff;
                background-color: #f0f7ff;
            }
            .page-btn.active {
                background: #1890ff;
                color: white;
                border-color: #1890ff;
                font-weight: 500;
            }
            .page-btn.disabled {
                cursor: not-allowed;
                color: #d9d9d9;
                background-color: #f5f5f5;
            }
            .page-ellipsis {
                color: #666;
                margin: 0 5px;
                user-select: none;
            }
            .page-jump {
                display: flex;
                align-items: center;
                gap: 5px;
                font-size: 14px;
                white-space: nowrap;
            }
            .jump-input {
                width: 50px;
                padding: 4px 8px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
                text-align: center;
                outline: none;
                transition: border-color 0.3s;
            }
            .jump-input:focus {
                border-color: #1890ff;
            }
            .jump-input::-webkit-inner-spin-button,
            .jump-input::-webkit-outer-spin-button {
                -webkit-appearance: none;
                margin: 0;
            }
        `;
        document.head.appendChild(style);
    }
    
    bindEvents() {
        // 页码大小变化
        this.container.querySelector('.page-size-select').addEventListener('change', (e) => {
            const pageSize = parseInt(e.target.value);
            this.handlePageChange(1, pageSize);
        });
        
        // 跳转页码
        const jumpInput = this.container.querySelector('.jump-input');
        const jumpBtn = this.container.querySelector('.page-jump .page-btn');
        
        jumpBtn.addEventListener('click', () => this.handleJump(jumpInput));
        jumpInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleJump(jumpInput);
            }
        });

        // 页码按钮点击
        this.container.querySelectorAll('.page-num').forEach(btn => {
            btn.addEventListener('click', () => {
                const page = parseInt(btn.dataset.page);
                this.handlePageChange(page, this.pageInfo.pageSize);
            });
        });

        // 上一页按钮
        const prevBtn = this.container.querySelector('.prev-btn');
        if (prevBtn && !prevBtn.disabled) {
            prevBtn.addEventListener('click', () => {
                this.handlePageChange(this.pageInfo.pageNum - 1, this.pageInfo.pageSize);
            });
        }

        // 下一页按钮
        const nextBtn = this.container.querySelector('.next-btn');
        if (nextBtn && !nextBtn.disabled) {
            nextBtn.addEventListener('click', () => {
                this.handlePageChange(this.pageInfo.pageNum + 1, this.pageInfo.pageSize);
            });
        }
    }
    
    handleJump(input) {
        const page = parseInt(input.value);
        const totalPages = Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
        if (page && page > 0 && page <= totalPages) {
            this.handlePageChange(page, this.pageInfo.pageSize);
        }
    }
    
    handlePageChange(page, size) {
        if (this.onPageChange) {
            this.onPageChange(page, size);
        }
    }
    
    update(pageInfo) {
        this.pageInfo = {
            ...this.pageInfo,
            ...pageInfo
        };
        this.render();
    }
    
    render() {
        if (!this.container) return;
        this.container.innerHTML = `
            <div class="pagination">
                <div class="pagination-info">
                    每页 
                    <select class="page-size-select">
                        <option value="10" ${this.pageInfo.pageSize === 10 ? 'selected' : ''}>10</option>
                        <option value="20" ${this.pageInfo.pageSize === 20 ? 'selected' : ''}>20</option>
                        <option value="50" ${this.pageInfo.pageSize === 50 ? 'selected' : ''}>50</option>
                        <option value="100" ${this.pageInfo.pageSize === 100 ? 'selected' : ''}>100</option>
                    </select> 
                    条
                </div>
                <div class="page-buttons">
                    ${this.renderPageButtons()}
                </div>
                <div class="page-jump">
                    跳至 <input type="number" class="jump-input" min="1" value="${this.pageInfo.pageNum}"> 页
                    <button class="page-btn">确定</button>
                </div>
                <div class="pagination-info">
                    共 ${this.pageInfo.total} 条
                </div>
            </div>
        `;
        
        // 绑定事件
        this.bindEvents();
    }
    
    renderPageButtons() {
        let html = '';
        
        // 上一页按钮
        html += `
            <button class="page-btn prev-btn ${!this.pageInfo.hasPrevious ? 'disabled' : ''}" 
                    ${!this.pageInfo.hasPrevious ? 'disabled' : ''}>
                上一页
            </button>
        `;
        
        // 计算总页数
        const totalPages = Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
        
        // 页码按钮
        let startPage = Math.max(1, this.pageInfo.pageNum - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        startPage = Math.max(1, endPage - 4);
        
        // 显示第一页
        if (startPage > 1) {
            html += `
                <button class="page-btn page-num" data-page="1">1</button>
                ${startPage > 2 ? '<span class="page-ellipsis">...</span>' : ''}
            `;
        }
        
        // 显示中间页码
        for (let i = startPage; i <= endPage; i++) {
            html += `
                <button class="page-btn page-num ${i === this.pageInfo.pageNum ? 'active' : ''}" 
                        data-page="${i}">
                    ${i}
                </button>
            `;
        }
        
        // 显示最后一页
        if (endPage < totalPages) {
            html += `
                ${endPage < totalPages - 1 ? '<span class="page-ellipsis">...</span>' : ''}
                <button class="page-btn page-num" data-page="${totalPages}">
                    ${totalPages}
                </button>
            `;
        }
        
        // 下一页按钮
        html += `
            <button class="page-btn next-btn ${!this.pageInfo.hasNext ? 'disabled' : ''}" 
                    ${!this.pageInfo.hasNext ? 'disabled' : ''}>
                下一页
            </button>
        `;
        
        return html;
    }
} 

export default Pagination;